package prefix.interceptor;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.apache.commons.lang3.StringUtils;

import play.mvc.Action;
import play.mvc.Http.Context;
import play.mvc.Result;
import play.mvc.With;
import prefix.platform.Constants;
import prefix.platform.session.LoginSession;

public class SecurityInterceptor {

    /**
     * Wraps the annotated action in an <code>AuthInterceptor</code>.
     */
    @With(AuthInterceptor.class)
    @Target({ ElementType.TYPE, ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Authentication {

    }

    public static class AuthInterceptor extends Action<Authentication> {
        @Override
        public Result call(Context ctx) throws Throwable {
            String uuid = ctx.session().get(Constants.UUID);
            String requestType = ctx.request().getHeader("X-Requested-With");
            // to do will handle the ajax session timeout later
//            if (requestType != null && requestType.equals("XMLHttpRequest")) 
            if (StringUtils.isNotEmpty(uuid)) {
                LoginSession ls = LoginSession.getSession(uuid);
                if (ls == null)
                    return unauthorized(views.html.defaultpages.unauthorized.render());
            } else
                return unauthorized(views.html.defaultpages.unauthorized.render());
            return delegate.call(ctx);
        }
    }

}
